import { ref } from 'vue'
import { queuedFetch } from '../utils/queuedRequest.js'

/**
 * Promise.allSettled polyfill for older browsers
 * 兼容低版本浏览器（Chrome < 76）
 */
if (!Promise.allSettled) {
  Promise.allSettled = function(promises) {
    return Promise.all(
      promises.map(promise =>
        Promise.resolve(promise)
          .then(value => ({ status: 'fulfilled', value }))
          .catch(reason => ({ status: 'rejected', reason }))
      )
    )
  }
}

/**
 * 机构号与名称的映射关系
 */
const ORG_NAME_MAP = {
  '00000': '东莞农村商业银行',
  '01000': '中堂支行',
  '02000': '望牛墩支行',
  '03000': '道滘支行',
  '04000': '洪梅支行',
  '05000': '麻涌支行',
  '06000': '万江支行',
  '07000': '虎门支行',
  '08000': '长安支行',
  '09000': '厚街支行',
  '10000': '沙田支行',
  '11000': '南城支行',
  '12000': '东城支行',
  '13000': '寮步支行',
  '14000': '大岭山支行',
  '15000': '大朗支行',
  '16000': '黄江支行',
  '17000': '樟木头支行',
  '18000': '清溪支行',
  '19000': '塘厦支行',
  '20000': '凤岗支行',
  '21000': '谢岗支行',
  '22000': '常平支行',
  '23000': '桥头支行',
  '24000': '横沥支行',
  '25000': '东坑支行',
  '26000': '企石支行',
  '27000': '石排支行',
  '28000': '茶山支行',
  '29000': '石碣支行',
  '30000': '高埗支行',
  '31000': '东联支行',
  '32000': '石龙支行',
  '33000': '松山湖科技支行',
  '37000': '总行(并表)',
  '38000': '中心支行',
  '39000': '私人银行部',
  '50000': '惠州支行',
  '51000': '清新支行',
  '52000': '南沙分行',
  '53000': '横琴分行',
  '55000': '滨海湾新区支行'
}

/**
 * 获取机构名称
 * @param {string} orgNo - 机构号
 * @returns {string} 机构名称
 */
const getOrgName = (orgNo) => {
  return ORG_NAME_MAP[orgNo] || orgNo
}

/**
 * 排除的机构号列表
 * 这些机构不参与统计
 */
const EXCLUDED_ORG_NOS = ['0A000','39000', '0B000', '91000', '92000', '90000', '82000', '81000', '71000', '72000', '37000', '00000', '00933']

/**
 * 生成排除机构号的SQL条件
 * @returns {string} SQL WHERE 条件
 */
const getOrgNoCondition = () => {
  const excludeList = EXCLUDED_ORG_NOS.map(org => `'${org}'`).join(',')
  return `p.org_no not in (${excludeList})`
}

/**
 * 获取上一个季度末日期
 * @param {string} bussDate - 当前日期，格式：YYYYMMDD
 * @returns {string} 上季度末日期，格式：YYYYMMDD
 */
const getLastQuarterEndDate = (bussDate) => {
  const year = parseInt(bussDate.substring(0, 4))
  const month = parseInt(bussDate.substring(4, 6))
  
  // 确定当前日期所属的季度，然后取上一个季度末
  // Q1: 1-3月 -> 上季度末: 上年12月31日
  // Q2: 4-6月 -> 上季度末: 当年3月31日
  // Q3: 7-9月 -> 上季度末: 当年6月30日
  // Q4: 10-12月 -> 上季度末: 当年9月30日
  
  let endYear = year
  let endMonth = 0
  let endDay = 0
  
  if (month >= 1 && month <= 3) {
    // Q1 -> 上年Q4末(12月31日)
    endYear = year - 1
    endMonth = 12
    endDay = 31
  } else if (month >= 4 && month <= 6) {
    // Q2 -> Q1末(3月31日)
    endMonth = 3
    endDay = 31
  } else if (month >= 7 && month <= 9) {
    // Q3 -> Q2末(6月30日)
    endMonth = 6
    endDay = 30
  } else {
    // Q4 -> Q3末(9月30日)
    endMonth = 9
    endDay = 30
  }
  
  const endMonthStr = endMonth.toString().padStart(2, '0')
  const endDayStr = endDay.toString().padStart(2, '0')
  
  return `${endYear}${endMonthStr}${endDayStr}`
}

/**
 * 计算期初日期（上上季度末）和期末日期（上季度末）
 * @param {string} bussDate - 当前日期，格式：YYYYMMDD
 * @returns {object} { endDate: 期末日期, startDate: 期初日期 }
 * 
 * 示例：
 * - 10月 -> 期末: 9月30日(Q3末), 期初: 6月30日(Q2末)
 * - 9月 -> 期末: 6月30日(Q2末), 期初: 3月31日(Q1末)
 * - 7月 -> 期末: 6月30日(Q2末), 期初: 3月31日(Q1末)
 */
const getQuarterDates = (bussDate) => {
  // 期末 = 上季度末
  const endDate = getLastQuarterEndDate(bussDate)
  
  // 期初 = 上上季度末（即期末日期的上季度末）
  const startDate = getLastQuarterEndDate(endDate)
  
  return { endDate, startDate }
}

/**
 * 计算期初日期（为了兼容旧代码，保留此函数）
 * @param {string} bussDate - 期末日期，格式：YYYYMMDD
 * @returns {string} 期初日期，格式：YYYYMMDD
 */
const getStartDate = (bussDate) => {
  const { startDate } = getQuarterDates(bussDate)
  return startDate
}

/**
 * 综合评分数据获取
 * 用于获取地图中间综合评分功能所需的各项指标数据
 */
export function useComprehensiveScore() {
  const isLoading = ref(false)
  const error = ref(null)
  const scoreData = ref({})

  /**
   * 执行SQL查询的通用方法
   */
  const executeSQL = async (sql, description = '') => {
    return new Promise((resolve, reject) => {
      try {
        console.log(`[综合评分] 开始执行查询: ${description}`)
        console.log(`[综合评分] SQL: ${sql}`)
        
        // 准备POST数据
        const postData = new URLSearchParams()
        postData.append('action', 'exesql')
        postData.append('jdbcName', 'amsedb')
        postData.append('enc', 'true')
        
        // SQL编码：先URL编码，再Base64编码
        const encodedSQL = btoa(encodeURIComponent(sql))
        postData.append('sql', encodedSQL)
        
        postData.append('pageIndex', 'undefined')
        postData.append('pageSize', '100')
        postData.append('isSys', 'false')
        postData.append('t', Date.now().toString())
        
        // API URL
        const apiUrl = `http://${window.location.host}/coolv/edatasource/jdbcmgr.do`
        
        // 使用队列化请求
        queuedFetch(apiUrl, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
            'X-Requested-With': 'XMLHttpRequest',
            'Accept': '*/*',
            'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8'
          },
          body: postData.toString()
        }, {
          name: `综合评分-${description}`,
          priority: 8
        })
        .then(response => {
          if (!response.ok) {
            throw new Error(`请求失败: ${response.status}`)
          }
          return response.json()
        })
        .then(jsonResponse => {
          console.log(`[综合评分] ${description} 查询成功:`, jsonResponse)
          resolve(jsonResponse)
        })
        .catch(e => {
          console.error(`[综合评分] ${description} 查询失败:`, e)
          reject(e)
        })
        
      } catch (e) {
        console.error(`[综合评分] ${description} 异常:`, e)
        reject(e)
      }
    })
  }

  /**
   * 综合评分指标配置
   * 每个指标包含：名称、取数SQL、计算说明
   * 
   * 字段顺序说明（所有 SQL 查询统一返回以下字段）：
   * row[0] = buss_dt      (业务日期)
   * row[1] = index_nm     (指标名称)
   * row[2] = org_no       (机构号)
   * row[3] = index_value  (指标值) ⭐ 主要使用
   * row[4] = ori          (来源)
   */
  const indicators = {
    // 1. 不良贷款率
    badLoanRate: {
      name: '不良贷款率',
      sql: (orgNo = '02000', bussDate = '20250831') => 
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where p.org_no ='${orgNo}' and buss_dt='${bussDate}' and p.index_nm = '不良贷款率' and p.ori='审计还原'`,
      sqlAll: (bussDate = '20250831') =>
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where ${getOrgNoCondition()} and p.buss_dt='${bussDate}' and p.index_nm = '不良贷款率' and p.ori='审计还原'`,
      type: 'single' // 单个值
    },
    
    // 2. 不良贷款余额
    badLoanBalance: {
      name: '不良贷款余额',
      sql: (orgNo = '02000', bussDate = '20250831') => 
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where p.org_no ='${orgNo}' and buss_dt='${bussDate}' and p.index_nm = '不良贷款余额' and p.ori='审计还原'`,
      sqlAll: (bussDate = '20250831') =>
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where ${getOrgNoCondition()} and p.buss_dt='${bussDate}' and p.index_nm = '不良贷款余额' and p.ori='审计还原'`,
      type: 'single'
    },
    
    // 3. 不良贷款增幅（需要期初期末对比，并加上核销金额）
    badLoanGrowth: {
      name: '不良贷款增幅',
      sql: (orgNo = '02000', bussDate = '20250831') => 
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where p.org_no ='${orgNo}' and buss_dt='${bussDate}' and p.index_nm = '不良贷款余额' and p.ori='审计还原'`,
      sqlAll: (bussDate = '20250831') =>
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where ${getOrgNoCondition()} and p.buss_dt='${bussDate}' and p.index_nm = '不良贷款余额' and p.ori='审计还原'`,
      sqlStart: (orgNo = '02000', startDate) =>
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where p.org_no ='${orgNo}' and buss_dt='${startDate}' and p.index_nm = '不良贷款余额' and p.ori='审计还原'`,
      sqlAllStart: (startDate) =>
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where ${getOrgNoCondition()} and p.buss_dt='${startDate}' and p.index_nm = '不良贷款余额' and p.ori='审计还原'`,
      // 核销金额查询（期初到期末之间）
      writeOffSQL: (orgNo = '02000', startDate, endDate) =>
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where p.org_no ='${orgNo}' and p.index_nm = '贷款核销月度余额' and p.ori='审计还原' and buss_dt>'${startDate}' and buss_dt<='${endDate}'`,
      writeOffSQLAll: (startDate, endDate) =>
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where ${getOrgNoCondition()} and p.index_nm = '贷款核销月度余额' and p.ori='审计还原' and buss_dt>'${startDate}' and buss_dt<='${endDate}'`,
      type: 'growthWithWriteOff'  // 带核销的增长型指标
    },
    
    // 3. 正常类贷款迁徙率
    normalLoanMigrationRate: {
      name: '正常类贷款迁徙率',
      sql: (orgNo = '02000', bussDate = '20250831') => 
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where p.org_no ='${orgNo}' and buss_dt='${bussDate}' and p.index_nm = '正常类贷款迁徙率'`,
      sqlAll: (bussDate = '20250831') =>
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where ${getOrgNoCondition()} and p.buss_dt='${bussDate}' and p.index_nm = '正常类贷款迁徙率'`,
      type: 'single'
    },
    
    // 4. 关注类贷款迁徙率
    specialMentionLoanMigrationRate: {
      name: '关注类贷款迁徙率',
      sql: (orgNo = '02000', bussDate = '20250831') => 
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where p.org_no ='${orgNo}' and buss_dt='${bussDate}' and p.index_nm = '关注类贷款迁徙率'`,
      sqlAll: (bussDate = '20250831') =>
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where ${getOrgNoCondition()} and p.buss_dt='${bussDate}' and p.index_nm = '关注类贷款迁徙率'`,
      type: 'single'
    },
    
    // 5. 次级类贷款迁徙率
    substandardLoanMigrationRate: {
      name: '次级类贷款迁徙率',
      sql: (orgNo = '02000', bussDate = '20250831') => 
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where p.org_no ='${orgNo}' and buss_dt='${bussDate}' and p.index_nm = '次级类贷款迁徙率'`,
      sqlAll: (bussDate = '20250831') =>
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where ${getOrgNoCondition()} and p.buss_dt='${bussDate}' and p.index_nm = '次级类贷款迁徙率'`,
      type: 'single'
    },
    
    // 6. 可疑类贷款迁徙率
    doubtfulLoanMigrationRate: {
      name: '可疑类贷款迁徙率',
      sql: (orgNo = '02000', bussDate = '20250831') => 
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where p.org_no ='${orgNo}' and buss_dt='${bussDate}' and p.index_nm = '可疑类贷款迁徙率'`,
      sqlAll: (bussDate = '20250831') =>
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where ${getOrgNoCondition()} and p.buss_dt='${bussDate}' and p.index_nm = '可疑类贷款迁徙率'`,
      type: 'single'
    },
    
    // 7. Top10客户贷款占比
    top10LoanRatio: {
      name: 'Top10客户贷款占比',
      sql: (orgNo = '02000', bussDate = '20250831') => 
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where p.org_no ='${orgNo}' and buss_dt='${bussDate}' and p.index_nm = '前十大贷款户金额占比' and p.ori='审计还原' group by buss_dt, index_nm, org_no, index_value, ori`,
      sqlAll: (bussDate = '20250831') =>
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where ${getOrgNoCondition()} and p.buss_dt='${bussDate}' and p.index_nm = '前十大贷款户金额占比' and p.ori='审计还原' group by buss_dt, index_nm, org_no, index_value, ori`,
      type: 'single'
    },
    
    // 7-1. Top10客户贷款余额
    top10LoanBalance: {
      name: 'Top10客户贷款余额',
      sql: (orgNo = '02000', bussDate = '20250831') => 
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where p.org_no ='${orgNo}' and buss_dt='${bussDate}' and p.index_nm = '前十大贷款户金额' and p.ori='审计还原' group by buss_dt, index_nm, org_no, index_value, ori`,
      sqlAll: (bussDate = '20250831') =>
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where ${getOrgNoCondition()} and p.buss_dt='${bussDate}' and p.index_nm = '前十大贷款户金额' and p.ori='审计还原' group by buss_dt, index_nm, org_no, index_value, ori`,
      type: 'single'
    },
    
    // 8. 逾期90天不良贷款余额占比
    overdue90DayRatio: {
      name: '逾期90天不良贷款余额占比',
      sql: (orgNo = '02000', bussDate = '20250831') => 
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where p.org_no ='${orgNo}' and buss_dt='${bussDate}' and p.index_nm = '逾期90天不良贷款余额占比'`,
      sqlAll: (bussDate = '20250831') =>
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where ${getOrgNoCondition()} and p.buss_dt='${bussDate}' and p.index_nm = '逾期90天不良贷款余额占比'`,
      type: 'single'
    },
    
    // 9. 关注类贷款占比
    concernLoanRatio: {
      name: '关注类贷款占比',
      sql: (orgNo = '02000', bussDate = '20250831') => 
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where p.org_no ='${orgNo}' and buss_dt='${bussDate}' and p.index_nm = '关注类贷款占比' and p.ori='审计还原'`,
      sqlAll: (bussDate = '20250831') =>
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where ${getOrgNoCondition()} and p.buss_dt='${bussDate}' and p.index_nm = '关注类贷款占比' and p.ori='审计还原'`,
      type: 'single'
    },
    
    // 9-1. 关注类贷款余额
    concernLoanBalance: {
      name: '关注类贷款余额',
      sql: (orgNo = '02000', bussDate = '20250831') => 
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where p.org_no ='${orgNo}' and buss_dt='${bussDate}' and p.index_nm = '关注类贷款余额' and p.ori='审计还原'`,
      sqlAll: (bussDate = '20250831') =>
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where ${getOrgNoCondition()} and p.buss_dt='${bussDate}' and p.index_nm = '关注类贷款余额' and p.ori='审计还原'`,
      type: 'single'
    },
    
    // 9-2. 关注类贷款增幅（需要期初期末对比）
    concernLoanGrowth: {
      name: '关注类贷款增幅',
      sql: (orgNo = '02000', bussDate = '20250831') => 
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where p.org_no ='${orgNo}' and buss_dt='${bussDate}' and p.index_nm = '关注类贷款余额' and p.ori='审计还原'`,
      sqlAll: (bussDate = '20250831') =>
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where ${getOrgNoCondition()} and p.buss_dt='${bussDate}' and p.index_nm = '关注类贷款余额' and p.ori='审计还原'`,
      sqlStart: (orgNo = '02000', startDate) =>
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where p.org_no ='${orgNo}' and buss_dt='${startDate}' and p.index_nm = '关注类贷款余额' and p.ori='审计还原'`,
      sqlAllStart: (startDate) =>
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where ${getOrgNoCondition()} and p.buss_dt='${startDate}' and p.index_nm = '关注类贷款余额' and p.ori='审计还原'`,
      type: 'growth'  // 增长型指标
    },
    
    // 10. 存款余额增速（需要期初期末对比）
    depositGrowth: {
      name: '存款余额增速',
      sql: (orgNo = '02000', bussDate = '20250831') => 
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where p.org_no ='${orgNo}' and p.buss_dt='${bussDate}' and p.index_nm = '各项存款余额' and p.ori='审计还原'`,
      sqlAll: (bussDate = '20250831') =>
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where ${getOrgNoCondition()} and p.buss_dt='${bussDate}' and p.index_nm = '各项存款余额' and p.ori='审计还原'`,
      sqlStart: (orgNo = '02000', startDate) =>
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where p.org_no ='${orgNo}' and p.buss_dt='${startDate}' and p.index_nm = '各项存款余额' and p.ori='审计还原'`,
      sqlAllStart: (startDate) =>
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where ${getOrgNoCondition()} and p.buss_dt='${startDate}' and p.index_nm = '各项存款余额' and p.ori='审计还原'`,
      type: 'growth'  // 增长型指标
    },
    
    // 10-1. 存款余额增加值（需要期初期末对比）
    depositIncrease: {
      name: '存款余额增加值',
      sql: (orgNo = '02000', bussDate = '20250831') => 
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where p.org_no ='${orgNo}' and p.buss_dt='${bussDate}' and p.index_nm = '各项存款余额' and p.ori='审计还原'`,
      sqlAll: (bussDate = '20250831') =>
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where ${getOrgNoCondition()} and p.buss_dt='${bussDate}' and p.index_nm = '各项存款余额' and p.ori='审计还原'`,
      sqlStart: (orgNo = '02000', startDate) =>
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where p.org_no ='${orgNo}' and p.buss_dt='${startDate}' and p.index_nm = '各项存款余额' and p.ori='审计还原'`,
      sqlAllStart: (startDate) =>
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where ${getOrgNoCondition()} and p.buss_dt='${startDate}' and p.index_nm = '各项存款余额' and p.ori='审计还原'`,
      type: 'increase'  // 增加值型指标（绝对值）
    },
    
    // 11. 低成本存款占比 (需要计算：分子/分母)
    lowCostDepositRatio: {
      name: '低成本存款占比',
      numeratorSQL: (orgNo = '02000', bussDate = '20250831') => 
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where p.org_no ='${orgNo}' and p.buss_dt='${bussDate}' and p.index_nm = '各项存款余额年日均余额' and p.ori='审计还原'`,
      numeratorSQLAll: (bussDate = '20250831') =>
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where ${getOrgNoCondition()} and p.buss_dt='${bussDate}' and p.index_nm = '各项存款余额年日均余额' and p.ori='审计还原'`,
      denominatorSQL: (orgNo = '02000', bussDate = '20250831') => 
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where p.org_no ='${orgNo}' and p.buss_dt='${bussDate}' and p.index_nm = '各项存款余额' and p.ori='审计还原'`,
      denominatorSQLAll: (bussDate = '20250831') =>
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where ${getOrgNoCondition()} and p.buss_dt='${bussDate}' and p.index_nm = '各项存款余额' and p.ori='审计还原'`,
      type: 'ratio'
    },
    
    // 12. 存款偏离度 (需要计算)
    depositDeviation: {
      name: '存款偏离度',
      monthEndSQL: (orgNo = '02000', bussDate = '20250831') => 
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where p.org_no ='${orgNo}' and buss_dt='${bussDate}' and p.index_nm='各项存款' and p.ori='财务指标结果表'`,
      monthEndSQLAll: (bussDate = '20250831') =>
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where ${getOrgNoCondition()} and p.buss_dt='${bussDate}' and p.index_nm='各项存款' and p.ori='财务指标结果表'`,
      monthAvgSQL: (orgNo = '02000', bussDate = '20250831') => 
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where p.org_no ='${orgNo}' and buss_dt='${bussDate}' and p.index_nm in ('个人存款月日均余额','单位存款月日均余额')`,
      monthAvgSQLAll: (bussDate = '20250831') =>
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where ${getOrgNoCondition()} and p.buss_dt='${bussDate}' and p.index_nm in ('个人存款月日均余额','单位存款月日均余额')`,
      type: 'deviation'
    },
    
    // 13. 新增贷款投放额（需要期初期末对比）
    newLoanAmount: {
      name: '新增贷款投放额',
      sql: (orgNo = '02000', bussDate = '20250831') => 
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where p.org_no ='${orgNo}' and buss_dt='${bussDate}' and p.index_nm = '各项贷款余额' and p.ori='审计还原'`,
      sqlAll: (bussDate = '20250831') =>
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where ${getOrgNoCondition()} and p.buss_dt='${bussDate}' and p.index_nm = '各项贷款余额' and p.ori='审计还原'`,
      sqlStart: (orgNo = '02000', startDate) =>
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where p.org_no ='${orgNo}' and buss_dt='${startDate}' and p.index_nm = '各项贷款余额' and p.ori='审计还原'`,
      sqlAllStart: (startDate) =>
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where ${getOrgNoCondition()} and p.buss_dt='${startDate}' and p.index_nm = '各项贷款余额' and p.ori='审计还原'`,
      type: 'increase'  // 增加值型指标
    },
    
    // 13-1. 各项贷款（需要期初期末对比）
    totalLoan: {
      name: '各项贷款',
      sql: (orgNo = '02000', bussDate = '20250831') => 
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where p.org_no ='${orgNo}' and buss_dt='${bussDate}' and p.index_nm in ('各项贷款') and p.ori='财务指标结果表'`,
      sqlAll: (bussDate = '20250831') =>
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where ${getOrgNoCondition()} and p.buss_dt='${bussDate}' and p.index_nm in ('各项贷款') and p.ori='财务指标结果表'`,
      sqlStart: (orgNo = '02000', startDate) =>
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where p.org_no ='${orgNo}' and buss_dt='${startDate}' and p.index_nm in ('各项贷款') and p.ori='财务指标结果表'`,
      sqlAllStart: (startDate) =>
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where ${getOrgNoCondition()} and p.buss_dt='${startDate}' and p.index_nm in ('各项贷款') and p.ori='财务指标结果表'`,
      type: 'growth'  // 增长型指标
    },
    
    // 14. 贷款户数增加值（需要期初期末对比）
    loanAccountIncrease: {
      name: '贷款户数增加值',
      sql: (orgNo = '02000', bussDate = '20250831') => 
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where p.org_no ='${orgNo}' and buss_dt='${bussDate}' and p.index_nm = '各支行贷款户数'`,
      sqlAll: (bussDate = '20250831') =>
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where ${getOrgNoCondition()} and p.buss_dt='${bussDate}' and p.index_nm = '各支行贷款户数'`,
      sqlStart: (orgNo = '02000', startDate) =>
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where p.org_no ='${orgNo}' and buss_dt='${startDate}' and p.index_nm = '各支行贷款户数'`,
      sqlAllStart: (startDate) =>
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where ${getOrgNoCondition()} and p.buss_dt='${startDate}' and p.index_nm = '各支行贷款户数'`,
      type: 'increase'  // 增加值型指标
    },
    
    // 14-1. 贷款户数增长率（需要期初期末对比）
    loanAccountGrowth: {
      name: '贷款户数增长率',
      sql: (orgNo = '02000', bussDate = '20250831') => 
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where p.org_no ='${orgNo}' and buss_dt='${bussDate}' and p.index_nm = '各支行贷款户数'`,
      sqlAll: (bussDate = '20250831') =>
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where ${getOrgNoCondition()} and p.buss_dt='${bussDate}' and p.index_nm = '各支行贷款户数'`,
      sqlStart: (orgNo = '02000', startDate) =>
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where p.org_no ='${orgNo}' and buss_dt='${startDate}' and p.index_nm = '各支行贷款户数'`,
      sqlAllStart: (startDate) =>
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where ${getOrgNoCondition()} and p.buss_dt='${startDate}' and p.index_nm = '各支行贷款户数'`,
      type: 'growth'  // 增长型指标
    },
    
    // 15. 中间业务收入绝对额（需要期初期末对比）
    intermediateIncomeAmount: {
      name: '中间业务收入绝对额',
      sql: (orgNo = '02000', bussDate = '20250831') => 
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where p.org_no ='${orgNo}' and buss_dt='${bussDate}' and p.index_nm = '手续费及佣金收入' and p.ori='利润表'`,
      sqlAll: (bussDate = '20250831') =>
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where ${getOrgNoCondition()} and p.buss_dt='${bussDate}' and p.index_nm = '手续费及佣金收入' and p.ori='利润表'`,
      sqlStart: (orgNo = '02000', startDate) =>
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where p.org_no ='${orgNo}' and buss_dt='${startDate}' and p.index_nm = '手续费及佣金收入' and p.ori='利润表'`,
      sqlAllStart: (startDate) =>
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where ${getOrgNoCondition()} and p.buss_dt='${startDate}' and p.index_nm = '手续费及佣金收入' and p.ori='利润表'`,
      type: 'increase'  // 增加值型指标
    },
    
    // 15-1. 中间业务收入占比 (需要计算：分子/分母)
    intermediateIncomeRatio: {
      name: '中间业务收入占比',
      numeratorSQL: (orgNo = '02000', bussDate = '20250831') => 
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where p.org_no ='${orgNo}' and buss_dt='${bussDate}' and p.index_nm = '手续费及佣金收入' and p.ori='利润表'`,
      numeratorSQLAll: (bussDate = '20250831') =>
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where ${getOrgNoCondition()} and p.buss_dt='${bussDate}' and p.index_nm = '手续费及佣金收入' and p.ori='利润表'`,
      denominatorSQL: (orgNo = '02000', bussDate = '20250831') => 
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where p.org_no ='${orgNo}' and buss_dt='${bussDate}' and p.index_nm = '一、营业收入' and p.ori='利润明细表'`,
      denominatorSQLAll: (bussDate = '20250831') =>
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where ${getOrgNoCondition()} and p.buss_dt='${bussDate}' and p.index_nm = '一、营业收入' and p.ori='利润明细表'`,
      type: 'ratio'
    },
    
    // 16. 中间业务收入增长率（需要期初期末对比）
    intermediateIncomeGrowth: {
      name: '中间业务收入增长率',
      sql: (orgNo = '02000', bussDate = '20250831') => 
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where p.org_no ='${orgNo}' and buss_dt='${bussDate}' and p.index_nm = '手续费及佣金收入' and p.ori='利润表'`,
      sqlAll: (bussDate = '20250831') =>
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where ${getOrgNoCondition()} and p.buss_dt='${bussDate}' and p.index_nm = '手续费及佣金收入' and p.ori='利润表'`,
      sqlStart: (orgNo = '02000', startDate) =>
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where p.org_no ='${orgNo}' and buss_dt='${startDate}' and p.index_nm = '手续费及佣金收入' and p.ori='利润表'`,
      sqlAllStart: (startDate) =>
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where ${getOrgNoCondition()} and p.buss_dt='${startDate}' and p.index_nm = '手续费及佣金收入' and p.ori='利润表'`,
      type: 'growth'  // 增长型指标
    },
    
    // 17. 稳定型中收占比 (需要计算：分子/分母)
    stableIncomeRatio: {
      name: '稳定型中收占比',
      numeratorSQL: (orgNo = '02000', bussDate = '20250831') => 
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where p.org_no ='${orgNo}' and buss_dt='${bussDate}' and p.index_nm in ('2.结算业务手续费收入','6.账户管理费收入','3.外汇业务手续费收入')`,
      numeratorSQLAll: (bussDate = '20250831') =>
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where ${getOrgNoCondition()} and p.buss_dt='${bussDate}' and p.index_nm in ('2.结算业务手续费收入','6.账户管理费收入','3.外汇业务手续费收入')`,
      denominatorSQL: (orgNo = '02000', bussDate = '20250831') => 
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where p.org_no ='${orgNo}' and buss_dt='${bussDate}' and p.index_nm = '手续费及佣金收入' and p.ori='利润表'`,
      denominatorSQLAll: (bussDate = '20250831') =>
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where ${getOrgNoCondition()} and p.buss_dt='${bussDate}' and p.index_nm = '手续费及佣金收入' and p.ori='利润表'`,
      type: 'ratio'
    },
    
    // 17-1. 稳定型中收绝对额（需要期初期末对比）
    stableIncomeAmount: {
      name: '稳定型中收绝对额',
      sql: (orgNo = '02000', bussDate = '20250831') => 
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where p.org_no ='${orgNo}' and buss_dt='${bussDate}' and p.index_nm in ('2.结算业务手续费收入','6.账户管理费收入','3.外汇业务手续费收入')`,
      sqlAll: (bussDate = '20250831') =>
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where ${getOrgNoCondition()} and p.buss_dt='${bussDate}' and p.index_nm in ('2.结算业务手续费收入','6.账户管理费收入','3.外汇业务手续费收入')`,
      sqlStart: (orgNo = '02000', startDate) =>
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where p.org_no ='${orgNo}' and buss_dt='${startDate}' and p.index_nm in ('2.结算业务手续费收入','6.账户管理费收入','3.外汇业务手续费收入')`,
      sqlAllStart: (startDate) =>
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where ${getOrgNoCondition()} and p.buss_dt='${startDate}' and p.index_nm in ('2.结算业务手续费收入','6.账户管理费收入','3.外汇业务手续费收入')`,
      type: 'increase'  // 增加值型指标（需要求和多条记录）
    },
    
    // 17-2. 稳定型中收增长率（需要期初期末对比）
    stableIncomeGrowth: {
      name: '稳定型中收增长率',
      sql: (orgNo = '02000', bussDate = '20250831') => 
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where p.org_no ='${orgNo}' and buss_dt='${bussDate}' and p.index_nm in ('2.结算业务手续费收入','6.账户管理费收入','3.外汇业务手续费收入')`,
      sqlAll: (bussDate = '20250831') =>
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where ${getOrgNoCondition()} and p.buss_dt='${bussDate}' and p.index_nm in ('2.结算业务手续费收入','6.账户管理费收入','3.外汇业务手续费收入')`,
      sqlStart: (orgNo = '02000', startDate) =>
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where p.org_no ='${orgNo}' and buss_dt='${startDate}' and p.index_nm in ('2.结算业务手续费收入','6.账户管理费收入','3.外汇业务手续费收入')`,
      sqlAllStart: (startDate) =>
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where ${getOrgNoCondition()} and p.buss_dt='${startDate}' and p.index_nm in ('2.结算业务手续费收入','6.账户管理费收入','3.外汇业务手续费收入')`,
      type: 'growth'  // 增长型指标（需要求和多条记录）
    },
    
    // 18. 人均利润 (需要计算：分子/分母，单位：万元)
    profitPerCapita: {
      name: '人均利润',
      numeratorSQL: (orgNo = '01000', bussDate = '20250831') => 
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where p.org_no ='${orgNo}' and buss_dt='${bussDate}' and p.index_nm='五、净利润（净亏损以“-”号填列）'  and p.ori='利润明细表'`,
      numeratorSQLAll: (bussDate = '20250831') =>
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where ${getOrgNoCondition()} and p.buss_dt='${bussDate}' and p.index_nm='五、净利润（净亏损以“-”号填列）' and p.ori='利润明细表'`,
      denominatorSQL: (orgNo = '01000', bussDate = '20250831') => 
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where p.org_no ='${orgNo}' and buss_dt='${bussDate}' and p.index_nm ='员工人数'`,
      denominatorSQLAll: (bussDate = '20250831') =>
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where ${getOrgNoCondition()} and p.buss_dt='${bussDate}' and p.index_nm ='员工人数'`,
      type: 'ratio',
      unit: 'wan'  // 单位：万元
    },
    
    // 19. 成本收入比 (需要计算：分子/分母)
    costIncomeRatio: {
      name: '成本收入比',
      numeratorSQL: (orgNo = '02000', bussDate = '20250831') => 
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where p.org_no ='${orgNo}' and p.buss_dt='${bussDate}' and p.index_nm ='6601业务及管理费用' and p.ori='利润明细表'`,
      numeratorSQLAll: (bussDate = '20250831') =>
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where ${getOrgNoCondition()} and p.buss_dt='${bussDate}' and p.index_nm ='6601业务及管理费用' and p.ori='利润明细表'`,
      denominatorSQL: (orgNo = '02000', bussDate = '20250831') => 
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where p.org_no ='${orgNo}' and p.buss_dt='${bussDate}' and p.index_nm ='一、营业收入' and p.ori='利润明细表'`,
      denominatorSQLAll: (bussDate = '20250831') =>
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where ${getOrgNoCondition()} and p.buss_dt='${bussDate}' and p.index_nm ='一、营业收入' and p.ori='利润明细表'`,
      type: 'ratio'
    },
    
    // 20. 风险合规得分（使用上季度末日期）
    riskComplianceScore: {
      name: '风险合规得分',
      sql: (orgNo = '02000', bussDate = '20250831') => 
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where p.ori='风险合规得分' and p.buss_dt='${bussDate}' and p.org_no='${orgNo}' and p.index_nm='风险合规得分'`,
      sqlAll: (bussDate = '20250831') =>
        `select p.buss_dt, p.index_nm, p.org_no, p.index_value, p.ori from audit_index_total p where p.ori='风险合规得分' and p.buss_dt='${bussDate}' and ${getOrgNoCondition()} and p.index_nm='风险合规得分'`,
      type: 'single'
    }
  }

  /**
   * 获取单个指标数据
   */
  const fetchSingleIndicator = async (key, config, orgNo = '02000', bussDate = '20250831') => {
    try {
      if (config.type === 'single' || config.type === 'multiple') {
        const sql = config.sql(orgNo, bussDate)
        const result = await executeSQL(sql, config.name)
        return { key, name: config.name, result, type: config.type, success: true }
      } else if (config.type === 'growth' || config.type === 'increase') {
        // 增长型或增加值型指标：需要获取期初和期末数据
        const startDate = getStartDate(bussDate)
        
        const endSQL = config.sql(orgNo, bussDate)
        const startSQL = config.sqlStart(orgNo, startDate)
        
        const endResult = await executeSQL(endSQL, `${config.name}-期末(${bussDate})`)
        const startResult = await executeSQL(startSQL, `${config.name}-期初(${startDate})`)
        
        return { 
          key, 
          name: config.name, 
          endResult,    // 期末数据
          startResult,  // 期初数据
          type: config.type,
          success: true 
        }
      } else if (config.type === 'growthWithWriteOff') {
        // 带核销的增长型指标：需要获取期初、期末和核销数据
        const startDate = getStartDate(bussDate)
        
        const endSQL = config.sql(orgNo, bussDate)
        const startSQL = config.sqlStart(orgNo, startDate)
        const writeOffSQL = config.writeOffSQL(orgNo, startDate, bussDate)
        
        const endResult = await executeSQL(endSQL, `${config.name}-期末(${bussDate})`)
        const startResult = await executeSQL(startSQL, `${config.name}-期初(${startDate})`)
        const writeOffResult = await executeSQL(writeOffSQL, `${config.name}-核销`)
        
        return { 
          key, 
          name: config.name, 
          endResult,       // 期末数据
          startResult,     // 期初数据
          writeOffResult,  // 核销数据
          type: config.type,
          success: true 
        }
      } else if (config.type === 'ratio') {
        // 需要分子和分母两次查询
        const numeratorSQL = config.numeratorSQL(orgNo, bussDate)
        const denominatorSQL = config.denominatorSQL(orgNo, bussDate)
        
        console.log(`[比率型指标] ${config.name} - 机构${orgNo}`)
        console.log(`  分子SQL: ${numeratorSQL}`)
        console.log(`  分母SQL: ${denominatorSQL}`)
        
        const numeratorResult = await executeSQL(numeratorSQL, `${config.name}-分子`)
        const denominatorResult = await executeSQL(denominatorSQL, `${config.name}-分母`)
        
        console.log(`  分子结果: ${numeratorResult?.datas?.length || 0} 条记录`)
        console.log(`  分母结果: ${denominatorResult?.datas?.length || 0} 条记录`)
        
        if (numeratorResult?.datas?.length > 0) {
          console.log(`  分子数据示例:`, numeratorResult.datas[0])
        }
        if (denominatorResult?.datas?.length > 0) {
          console.log(`  分母数据示例:`, denominatorResult.datas[0])
        }
        
        // 保存单位信息
        const result = { 
          key, 
          name: config.name, 
          numeratorResult, 
          denominatorResult,
          type: config.type,
          success: true 
        }
        
        // 如果配置了单位，保存到结果中
        if (config.unit) {
          result.unit = config.unit
        }
        
        return result
      } else if (config.type === 'deviation') {
        // 存款偏离度需要月末和月均两次查询
        const monthEndSQL = config.monthEndSQL(orgNo, bussDate)
        const monthAvgSQL = config.monthAvgSQL(orgNo, bussDate)
        
        const monthEndResult = await executeSQL(monthEndSQL, `${config.name}-月末`)
        const monthAvgResult = await executeSQL(monthAvgSQL, `${config.name}-月均`)
        
        return { 
          key, 
          name: config.name, 
          monthEndResult, 
          monthAvgResult, 
          success: true 
        }
      }
    } catch (error) {
      console.error(`[综合评分] ${config.name} 获取失败:`, error)
      return { key, name: config.name, error, success: false }
    }
  }

  /**
   * 获取所有支行机构号
   */
  const fetchAllOrgNos = async () => {
    try {
      // 明确指定字段：org_no
      const sql = `select distinct org_no from audit_index_total where org_no != '00000' order by org_no`
      const result = await executeSQL(sql, '获取所有机构号')
      
      if (result && result.datas && result.datas.length > 0) {
        // 返回机构号数组（第1列：org_no）
        return result.datas.map(row => row[0])
      }
      return []
    } catch (error) {
      console.error('[综合评分] 获取机构号列表失败:', error)
      return []
    }
  }

  /**
   * 获取单个机构的所有指标数据
   */
  const fetchAllIndicators = async (orgNo = '02000', bussDate = '20250831') => {
    try {
      console.log(`[综合评分] 开始获取机构 ${orgNo} 的所有指标数据...`)

      // 并行获取所有指标
      const promises = Object.entries(indicators).map(([key, config]) => 
        fetchSingleIndicator(key, config, orgNo, bussDate)
      )

      const results = await Promise.allSettled(promises)
      
      // 处理结果
      const data = {}
      let successCount = 0
      let failCount = 0
      
      results.forEach((result, index) => {
        if (result.status === 'fulfilled' && result.value) {
          const value = result.value
          data[value.key] = value
          successCount++
        } else if (result.status === 'rejected') {
          const indicatorKey = Object.keys(indicators)[index]
          const indicatorName = indicators[indicatorKey]?.name || indicatorKey
          console.warn(`[综合评分] ⚠️ 机构 ${orgNo} 的指标 "${indicatorName}" 获取失败:`, result.reason)
          failCount++
        }
      })

      console.log(`[综合评分] 机构 ${orgNo} 数据获取完成: ✅ 成功 ${successCount}项, ❌ 失败 ${failCount}项`)
      return data
    } catch (err) {
      console.error(`[综合评分] 机构 ${orgNo} 获取指标数据失败:`, err)
      throw err
    }
  }

  /**
   * 获取单个指标的所有支行数据
   */
  const fetchIndicatorForAllBranches = async (key, config, bussDate, startDate = null) => {
    try {
      if (config.type === 'single' || config.type === 'multiple') {
        const sql = config.sqlAll(bussDate)
        const result = await executeSQL(sql, `${config.name}-所有支行`)
        return { key, name: config.name, result, type: config.type, success: true }
      } else if (config.type === 'growth' || config.type === 'increase') {
        // 增长型指标或增加值型指标：需要获取期初和期末数据
        // 如果没有传入期初日期，则计算期初日期（向后兼容）
        const actualStartDate = startDate || getStartDate(bussDate)
        
        const endSQL = config.sqlAll(bussDate)
        const startSQL = config.sqlAllStart(actualStartDate)
        
        const endResult = await executeSQL(endSQL, `${config.name}-所有支行-期末(${bussDate})`)
        const startResult = await executeSQL(startSQL, `${config.name}-所有支行-期初(${actualStartDate})`)
        
        return { 
          key, 
          name: config.name, 
          endResult,    // 期末数据
          startResult,  // 期初数据
          type: config.type,
          success: true 
        }
      } else if (config.type === 'growthWithWriteOff') {
        // 带核销的增长型指标：需要获取期初、期末和核销数据
        // 如果没有传入期初日期，则计算期初日期（向后兼容）
        const actualStartDate = startDate || getStartDate(bussDate)
        
        const endSQL = config.sqlAll(bussDate)
        const startSQL = config.sqlAllStart(actualStartDate)
        const writeOffSQL = config.writeOffSQLAll(actualStartDate, bussDate)
        
        const endResult = await executeSQL(endSQL, `${config.name}-所有支行-期末(${bussDate})`)
        const startResult = await executeSQL(startSQL, `${config.name}-所有支行-期初(${actualStartDate})`)
        const writeOffResult = await executeSQL(writeOffSQL, `${config.name}-所有支行-核销`)
        
        return { 
          key, 
          name: config.name, 
          endResult,       // 期末数据
          startResult,     // 期初数据
          writeOffResult,  // 核销数据
          type: config.type,
          success: true 
        }
      } else if (config.type === 'ratio') {
        const numeratorSQL = config.numeratorSQLAll(bussDate)
        const denominatorSQL = config.denominatorSQLAll(bussDate)
        
        console.log(`[比率型指标-批量] ${config.name}`)
        console.log(`  分子SQL: ${numeratorSQL}`)
        console.log(`  分母SQL: ${denominatorSQL}`)
        
        const numeratorResult = await executeSQL(numeratorSQL, `${config.name}-所有支行-分子`)
        const denominatorResult = await executeSQL(denominatorSQL, `${config.name}-所有支行-分母`)
        
        console.log(`  分子结果: ${numeratorResult?.datas?.length || 0} 条记录`)
        console.log(`  分母结果: ${denominatorResult?.datas?.length || 0} 条记录`)
        
        // 保存单位信息
        const result = { 
          key, 
          name: config.name, 
          numeratorResult, 
          denominatorResult,
          type: config.type,
          success: true 
        }
        
        // 如果配置了单位，保存到结果中
        if (config.unit) {
          result.unit = config.unit
        }
        
        return result
      } else if (config.type === 'deviation') {
        const monthEndSQL = config.monthEndSQLAll(bussDate)
        const monthAvgSQL = config.monthAvgSQLAll(bussDate)
        
        const monthEndResult = await executeSQL(monthEndSQL, `${config.name}-所有支行-月末`)
        const monthAvgResult = await executeSQL(monthAvgSQL, `${config.name}-所有支行-月均`)
        
        return { 
          key, 
          name: config.name, 
          monthEndResult, 
          monthAvgResult,
          type: config.type,
          success: true 
        }
      }
    } catch (error) {
      console.error(`[综合评分] ${config.name} 所有支行获取失败:`, error)
      return { key, name: config.name, error, success: false }
    }
  }

  /**
   * 按机构号分组数据
   */
  const groupDataByOrg = (indicatorData) => {
    const grouped = {}
    
    // 遍历每个指标
    Object.entries(indicatorData).forEach(([key, data]) => {
      if (!data.success) {
        // 如果指标获取失败，标记所有支行的该指标都失败
        return
      }

      if (data.type === 'single' || data.type === 'multiple') {
        // 单值或多值类型
        if (data.result && data.result.datas) {
          data.result.datas.forEach(row => {
            const orgNo = row[2] // 机构号在第3列（索引2）
            if (!grouped[orgNo]) grouped[orgNo] = {}
            
            // 为该机构创建指标数据
            if (!grouped[orgNo][key]) {
              grouped[orgNo][key] = {
                key,
                name: data.name,
                type: data.type,  // 添加类型标识
                success: true,
                result: {
                  isselect: true,
                  totalcount: 0,
                  pageIndex: 0,
                  datas: []
                }
              }
            }
            grouped[orgNo][key].result.datas.push(row)
            grouped[orgNo][key].result.totalcount++
          })
        }
      } else if (data.type === 'growth' || data.type === 'increase') {
        // 增长型或增加值型指标：需要分别处理期初和期末数据
        const processGrowthPart = (result, partType) => {
          if (result && result.datas) {
            result.datas.forEach(row => {
              const orgNo = row[2]
              if (!grouped[orgNo]) grouped[orgNo] = {}
              if (!grouped[orgNo][key]) {
                grouped[orgNo][key] = {
                  key,
                  name: data.name,
                  type: data.type,  // 添加类型标识（growth 或 increase）
                  success: true,
                  endResult: { isselect: true, totalcount: 0, pageIndex: 0, datas: [] },    // 期末
                  startResult: { isselect: true, totalcount: 0, pageIndex: 0, datas: [] }   // 期初
                }
              }
              if (partType === 'end') {
                grouped[orgNo][key].endResult.datas.push(row)
                grouped[orgNo][key].endResult.totalcount++
              } else {
                grouped[orgNo][key].startResult.datas.push(row)
                grouped[orgNo][key].startResult.totalcount++
              }
            })
          }
        }
        processGrowthPart(data.endResult, 'end')
        processGrowthPart(data.startResult, 'start')
      } else if (data.type === 'growthWithWriteOff') {
        // 带核销的增长型指标：需要分别处理期初、期末和核销数据
        const processGrowthWithWriteOffPart = (result, partType) => {
          if (result && result.datas) {
            result.datas.forEach(row => {
              const orgNo = row[2]
              if (!grouped[orgNo]) grouped[orgNo] = {}
              if (!grouped[orgNo][key]) {
                grouped[orgNo][key] = {
                  key,
                  name: data.name,
                  type: data.type,
                  success: true,
                  endResult: { isselect: true, totalcount: 0, pageIndex: 0, datas: [] },       // 期末
                  startResult: { isselect: true, totalcount: 0, pageIndex: 0, datas: [] },     // 期初
                  writeOffResult: { isselect: true, totalcount: 0, pageIndex: 0, datas: [] }   // 核销
                }
              }
              if (partType === 'end') {
                grouped[orgNo][key].endResult.datas.push(row)
                grouped[orgNo][key].endResult.totalcount++
              } else if (partType === 'start') {
                grouped[orgNo][key].startResult.datas.push(row)
                grouped[orgNo][key].startResult.totalcount++
              } else if (partType === 'writeOff') {
                grouped[orgNo][key].writeOffResult.datas.push(row)
                grouped[orgNo][key].writeOffResult.totalcount++
              }
            })
          }
        }
        processGrowthWithWriteOffPart(data.endResult, 'end')
        processGrowthWithWriteOffPart(data.startResult, 'start')
        processGrowthWithWriteOffPart(data.writeOffResult, 'writeOff')
      } else if (data.type === 'ratio') {
        // 比率类型，需要分别处理分子和分母
        const processRatioPart = (result, partType) => {
          if (result && result.datas) {
            result.datas.forEach(row => {
              const orgNo = row[2]
              if (!grouped[orgNo]) grouped[orgNo] = {}
              if (!grouped[orgNo][key]) {
                grouped[orgNo][key] = {
                  key,
                  name: data.name,
                  type: 'ratio',  // 添加类型标识
                  success: true,
                  numeratorResult: { isselect: true, totalcount: 0, pageIndex: 0, datas: [] },
                  denominatorResult: { isselect: true, totalcount: 0, pageIndex: 0, datas: [] }
                }
              }
              if (partType === 'numerator') {
                grouped[orgNo][key].numeratorResult.datas.push(row)
                grouped[orgNo][key].numeratorResult.totalcount++
              } else {
                grouped[orgNo][key].denominatorResult.datas.push(row)
                grouped[orgNo][key].denominatorResult.totalcount++
              }
            })
          }
        }
        processRatioPart(data.numeratorResult, 'numerator')
        processRatioPart(data.denominatorResult, 'denominator')
      } else if (data.type === 'deviation') {
        // 偏离度类型
        const processDeviationPart = (result, partType) => {
          if (result && result.datas) {
            result.datas.forEach(row => {
              const orgNo = row[2]
              if (!grouped[orgNo]) grouped[orgNo] = {}
              if (!grouped[orgNo][key]) {
                grouped[orgNo][key] = {
                  key,
                  name: data.name,
                  type: 'deviation',  // 添加类型标识
                  success: true,
                  monthEndResult: { isselect: true, totalcount: 0, pageIndex: 0, datas: [] },
                  monthAvgResult: { isselect: true, totalcount: 0, pageIndex: 0, datas: [] }
                }
              }
              if (partType === 'monthEnd') {
                grouped[orgNo][key].monthEndResult.datas.push(row)
                grouped[orgNo][key].monthEndResult.totalcount++
              } else {
                grouped[orgNo][key].monthAvgResult.datas.push(row)
                grouped[orgNo][key].monthAvgResult.totalcount++
              }
            })
          }
        }
        processDeviationPart(data.monthEndResult, 'monthEnd')
        processDeviationPart(data.monthAvgResult, 'monthAvg')
      }
    })

    return grouped
  }

  /**
   * 获取所有支行的所有指标数据（一次性获取）
   */
  const fetchAllBranchesData = async (bussDate = '20250831') => {
    isLoading.value = true
    error.value = null
    scoreData.value = {}

    try {
      // 将传入的日期转换为季度末日期和期初日期
      const { endDate, startDate } = getQuarterDates(bussDate)
      
      console.log('[综合评分] 开始一次性获取所有支行数据...')
      console.log(`[综合评分] 输入日期: ${bussDate}`)
      console.log(`[综合评分] 期末日期(上季度末): ${endDate}`)
      console.log(`[综合评分] 期初日期(上上季度末): ${startDate}`)
      console.log(`[综合评分] 策略: ${Object.keys(indicators).length}个请求，每个请求包含所有支行的数据`)

      // 并行获取所有指标的所有支行数据（使用季度末日期和期初日期）
      const promises = Object.entries(indicators).map(([key, config]) => 
        fetchIndicatorForAllBranches(key, config, endDate, startDate)
      )

      const results = await Promise.allSettled(promises)
      
      // 整理指标数据
      const indicatorData = {}
      let successCount = 0
      let failCount = 0
      
      results.forEach((result, index) => {
        if (result.status === 'fulfilled' && result.value) {
          const value = result.value
          indicatorData[value.key] = value
          successCount++
        } else if (result.status === 'rejected') {
          const indicatorKey = Object.keys(indicators)[index]
          const indicatorName = indicators[indicatorKey]?.name || indicatorKey
          console.error(`[综合评分] ❌ 指标 "${indicatorName}" 获取失败:`, result.reason)
          failCount++
          
          // 即使失败也继续处理其他指标，不中断整个流程
        }
      })

      console.log(`[综合评分] 所有指标数据获取完成: ✅ 成功 ${successCount}/${Object.keys(indicators).length}项, ❌ 失败 ${failCount}项`)
      console.log('[综合评分] 开始按机构号分组...')

      // 按机构号分组
      const grouped = groupDataByOrg(indicatorData)
      
      // 为每个支行补充缺失的关注类贷款和迁徙率指标（赋值为0）
      const zeroValueKeys = [
        'concernLoanRatio', 'concernLoanBalance', 'concernLoanGrowth',
        'normalLoanMigrationRate', 'specialMentionLoanMigrationRate', 
        'substandardLoanMigrationRate', 'doubtfulLoanMigrationRate'
      ]
      
      Object.keys(grouped).forEach(orgNo => {
        zeroValueKeys.forEach(key => {
          if (!grouped[orgNo][key]) {
            // 如果该指标不存在，创建一个0值对象
            const config = indicators[key]
            if (config.type === 'growth') {
              // 增长型指标
              grouped[orgNo][key] = {
                key,
                name: config.name,
                type: 'growth',
                success: true,
                endResult: {
                  isselect: true,
                  totalcount: 1,
                  pageIndex: 0,
                  datas: [[null, null, orgNo, 0]]
                },
                startResult: {
                  isselect: true,
                  totalcount: 1,
                  pageIndex: 0,
                  datas: [[null, null, orgNo, 0]]
                }
              }
            } else {
              // 单值型指标
              grouped[orgNo][key] = {
                key,
                name: config.name,
                type: 'single',
                success: true,
                result: {
                  isselect: true,
                  totalcount: 1,
                  pageIndex: 0,
                  datas: [[null, null, orgNo, 0]]
                }
              }
            }
          }
        })
      })

      scoreData.value = grouped
      
      const orgCount = Object.keys(grouped).length
      console.log(`[综合评分] 数据分组完成，共 ${orgCount} 个支行`)
      console.log('[综合评分] 支行列表:', Object.keys(grouped))
      
      // 返回数据和实际使用的日期
      return {
        data: grouped,
        endDate: endDate,  // 期末日期（上季度末）
        startDate: startDate  // 期初日期（上上季度末）
      }
    } catch (err) {
      error.value = err
      console.error('[综合评分] 获取所有支行数据失败:', err)
      throw err
    } finally {
      isLoading.value = false
    }
  }

  /**
   * 获取指标列表（用于显示）
   */
  const getIndicatorList = () => {
    return Object.entries(indicators).map(([key, config]) => ({
      key,
      name: config.name,
      type: config.type
    }))
  }

  return {
    isLoading,
    error,
    scoreData,
    indicators,
    fetchAllIndicators,
    fetchAllBranchesData,
    fetchAllOrgNos,
    fetchSingleIndicator,
    getIndicatorList,
    executeSQL,
    getOrgName
  }
}

